package com.stef.MMH;

import java.io.*;

import javax.persistence.EntityManager;
import javax.servlet.*;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Query;
import com.stef.MMH.datatypes.House;
import com.stef.MMH.datatypes.User;

import java.net.*;
import java.util.*;

/**
 * Simple example of session tracking. See the shopping cart example for a more
 * detailed one.
 * <P>
 * Part of tutorial on servlets and JSP that appears at
 * http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/ 1999 Marty Hall; may be
 * freely used or adapted.
 */

public class ManageMyHouseServlet extends HttpServlet {

	boolean validRequest = true;
	HttpServletResponse resp;
	HttpServletRequest req;
	HttpSession session;

	EntityManager em = EmfHolder.getEntityManager();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		session = request.getSession(false);
		response.setContentType("text/html");

		this.resp = response;
		this.req = request;

		if (session.isNew()) {
			badRequest();
			validRequest = false;
		}

		if (validRequest) {
			goodRequest();
		}

	}

	public void badRequest() throws IOException {
		resp.getWriter().print(":(");

	}

	public void goodRequest() throws IOException {

		User user = (User) session.getAttribute("USER");
		user = (User) em.createQuery("SELECT u FROM User u WHERE u.email =\"" + user.getEmail() +"\"").getSingleResult();

		House myHouse = new House("TEST HOUSE", user.getEmail());

		if (!em.getTransaction().isActive()) {
			em.getTransaction().begin();
		}
		em.persist(myHouse);
		
		myHouse.addInhabitant(user.getEmail());
		
		StringBuilder sb = new StringBuilder();
		sb.append("<html><body><h1>Good Job! "
				+ URLDecoder.decode(user.getRealName(), "UTF-8") + "</h1>\n");
		sb.append("<a href=\"createhouse\">Create House</a>\n<br />");
		sb.append("<a href=\"gotomyhouse\">Go To My House</a>\n");
		sb.append("</body></html>");
		resp.getWriter().println(sb.toString());
		session.setAttribute("USER", user);
		em.getTransaction().commit();
		
		em.getTransaction().begin();
		try{
			em.persist(user);
		} catch (Exception e){
			System.out.println("OBI NOBI");
		}
		user.setMyHouseKey(myHouse);
		System.out.println(user.getMyHouseKey().getOwnerEmail());
		em.flush();
		em.getTransaction().commit();
		user = (User) em.createQuery("SELECT u FROM User u WHERE u.email =\"" + user.getEmail() +"\"").getSingleResult();
		System.out.println(user.getMyHouseKey().getOwnerEmail());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}